#pragma warning disable 429

using UnityEditor;
using UnityEngine;
using System;
using System.Globalization;
using System.Collections;
using System.IO;

public class UTVPAssetPostprocessor : AssetPostprocessor {

	void OnPreprocessTexture()
	{
		if (assetPath.IndexOf("Resources/ukag") < 0)
			return;
		TextureImporter importer = (TextureImporter)assetImporter;
		string fileName = assetPath.Substring(assetPath.LastIndexOf('/') + 1);
		if (UTVPConfig.ImportConfig_2DImagePref == "" || fileName.IndexOf(UTVPConfig.ImportConfig_2DImagePref) == 0)
		{
			fileName = fileName.ToLower();
			importer.textureType = TextureImporterType.Advanced;
			importer.generateCubemap = TextureImporterGenerateCubemap.None;
			importer.mipmapEnabled = false;
			importer.npotScale = TextureImporterNPOTScale.None;
			importer.filterMode = FilterMode.Bilinear;
			importer.anisoLevel = 1;
			if (importer.textureFormat != TextureImporterFormat.Alpha8
				&& importer.textureFormat != TextureImporterFormat.RGB16
				&& importer.textureFormat != TextureImporterFormat.RGB24
				&& importer.textureFormat != TextureImporterFormat.DXT1)
				importer.alphaIsTransparency = true;
			if (fileName.IndexOf("mask") >= 0 || fileName.IndexOf("rule") >= 0)
			{
				importer.textureFormat = TextureImporterFormat.Alpha8;
				importer.wrapMode = TextureWrapMode.Clamp;
			}
		}
	}
	
	void OnPreprocessAudio()
	{
		if (assetPath.IndexOf("Resources/ukag") < 0)
			return;
		AudioImporter importer = (AudioImporter)assetImporter;
		string fileName = assetPath.Substring(assetPath.LastIndexOf('/') + 1);
		if (UTVPConfig.ImportConfig_2DAudioPref == "" || fileName.IndexOf(UTVPConfig.ImportConfig_2DAudioPref) == 0)
		{
			importer.threeD = false;
        }
		
		if (fileName.ToLower().IndexOf("bgm") >= 0 || fileName.ToLower().IndexOf("se") >= 0)
			importer.loadType = AudioImporterLoadType.StreamFromDisc;
		else if (assetPath.ToLower().IndexOf("/voice/") >= 0)
		{
			importer.loadType = AudioImporterLoadType.DecompressOnLoad;
			importer.compressionBitrate = 64 * 1024;
			//importer.loadType = AudioImporterLoadType.CompressedInMemory; 
		}
	}
	
	void OnPostprocessAudio(AudioClip clip) {
		if (assetPath.IndexOf("Resources/ukag") < 0)
			return;
		string sliPath = assetPath.Substring(0, assetPath.LastIndexOf('.')) + ".wav.sli";
		string newpath = assetPath.Substring(0, assetPath.LastIndexOf('.')) + ".txt";
		if (AssetDatabase.LoadMainAssetAtPath(sliPath) != null)
		{
			// 下面这两行会在控制台输出error,但是实际上是可以工作的
			AssetDatabase.MoveAsset(sliPath, newpath);
			AssetDatabase.Refresh();
			AssetDatabase.ImportAsset(newpath, ImportAssetOptions.ForceUpdate);
		}
	}
	
	static void OnPostprocessAllAssets(string[] importedAssets,
												string[] deletedAssets,
												string[] movedAssets,
												string[] movedFromPath)
	{
		for (int i=0; i<importedAssets.Length; i++)
		{
			string assetPath = importedAssets[i];
			if (assetPath.IndexOf("Resources/ukag") < 0)
				continue;
			if (assetPath.ToLower().EndsWith(".fnt"))
				ImportFontData(assetPath);
		}
	}

	[MenuItem("Assets/UKag/Create Font Asset")]
	static void CreateFontAsset()
	{
		if (Selection.activeObject == null || !(Selection.activeObject is TextAsset))
			return;
		
		string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
		if (assetPath.ToLower().EndsWith(".fnt"))
			ImportFontData(assetPath);
	}

	public static void ImportFontData(string fntpath)
	{
		string[] fntData = File.ReadAllLines(fntpath);
		UTVPBMFontInfo fontInfo = new UTVPBMFontInfo();
		fontInfo.ImageName = GetStrValueFromFntStr(fntData[2], "file");
		fontInfo.Face = GetStrValueFromFntStr(fntData[0], "face");
		fontInfo.Size = GetIntValueFromFntStr(fntData[0], "size");
		fontInfo.Bold = GetIntValueFromFntStr(fntData[0], "bold") == 1;
		fontInfo.Italic = GetIntValueFromFntStr(fntData[0], "italic") == 1;
		fontInfo.LineHeight = GetIntValueFromFntStr(fntData[1], "lineHeight");
		fontInfo.BaseHeight = GetIntValueFromFntStr(fntData[1], "base");
		fontInfo.ScaleW = GetIntValueFromFntStr(fntData[1], "scaleW");
		fontInfo.ScaleH = GetIntValueFromFntStr(fntData[1], "scaleH");
		fontInfo.Glyphs = new UTVPGlyphInfo[fntData.Length - 4];
		//Debug.Log("fontInfo " + fontInfo.imageName + " # " + fontInfo.face + " # " + fontInfo.size + " # " + fontInfo.baseHeight + " # " + fontInfo.lineHeight);
		
		UTVPGlyphInfo glyphInfo;
		for( int i=4; i<fntData.Length; i++)
		{
			if (fntData[i] == null || fntData[i].Length == 0)
				continue;
			glyphInfo = new UTVPGlyphInfo();
			glyphInfo.Ch = GetIntValueFromFntStr(fntData[i], "id");
			glyphInfo.X = GetIntValueFromFntStr(fntData[i], "x");
			glyphInfo.Y = GetIntValueFromFntStr(fntData[i], "y");
			glyphInfo.Width = GetIntValueFromFntStr(fntData[i], "width");
			glyphInfo.Height = GetIntValueFromFntStr(fntData[i], "height");
			glyphInfo.XOffset = GetIntValueFromFntStr(fntData[i], "xoffset");
			glyphInfo.YOffset = GetIntValueFromFntStr(fntData[i], "yoffset");
			glyphInfo.XAdvance = GetIntValueFromFntStr(fntData[i], "xadvance");
			fontInfo.Glyphs[i - 4] = glyphInfo;
			//if (i < 100)
			//	Debug.Log("glyphInfo " + glyphInfo.ch + " # " + glyphInfo.x + " # " + glyphInfo.y + " # " + glyphInfo.width + " # " + glyphInfo.height);
		}
		
		string fontPath = fntpath.Substring(0, fntpath.Length - 4);
		Texture2D texture = null;
		if (File.Exists (fontPath + "_0.png"))
			texture = AssetDatabase.LoadAssetAtPath(fontPath + "_0.png", typeof(Texture2D)) as Texture2D;
		else if (File.Exists (fontPath + "_0.tga"))
			texture = AssetDatabase.LoadAssetAtPath(fontPath + "_0.png", typeof(Texture2D)) as Texture2D;
		else if (File.Exists (fontPath + ".png"))
			texture = AssetDatabase.LoadAssetAtPath(fontPath + "_0.png", typeof(Texture2D)) as Texture2D;
		else if (File.Exists (fontPath + ".tga"))
			texture = AssetDatabase.LoadAssetAtPath(fontPath + "_0.png", typeof(Texture2D)) as Texture2D;
		UTVPBMFontInfoAsset fontInfoAsset = null;
		if (File.Exists (fontPath + ".asset")) {
			fontInfoAsset = AssetDatabase.LoadAssetAtPath (fontPath + ".asset", typeof(UTVPBMFontInfoAsset)) as UTVPBMFontInfoAsset;
			fontInfoAsset.FontInfo = fontInfo;
			fontInfoAsset.Texture = texture;
			EditorUtility.SetDirty(fontInfoAsset);
			AssetDatabase.SaveAssets();
		} else {
			fontInfoAsset = ScriptableObject.CreateInstance<UTVPBMFontInfoAsset> ();
			fontInfoAsset.FontInfo = fontInfo;
			fontInfoAsset.Texture = texture;
			AssetDatabase.CreateAsset(fontInfoAsset, fontPath + ".asset");
		}
		AssetDatabase.Refresh();
	}
	
	
	private static string GetStrValueFromFntStr(string str, string key)
	{
		int pos = str.IndexOf(key);
		if (pos < 0)
			return null;
		pos += key.Length + 2;
		int posEnd = str.IndexOf('"', pos);
		if (posEnd < 0)
			return null;
		return str.Substring(pos, posEnd - pos);
	}
	
	private static int GetIntValueFromFntStr(string str, string key)
	{
		int[] result = GetIntValueArrFromFntStr(str, key);
		if (result == null || result.Length == 0)
			return 0;
		else
			return result[0];
	}

	private static int[] GetIntValueArrFromFntStr(string str, string key)
	{
		int pos = str.IndexOf(key);
		if (pos < 0)
			return null;
		pos += key.Length + 1;
		int posEnd = str.IndexOf(' ', pos);
		if (posEnd < 0)
			return null;
		string[] intStrArr = str.Substring(pos, posEnd - pos).Split(',');
		int[] intArr = new int[intStrArr.Length];
		int parseResult = 0;
		for (int i=0; i<intStrArr.Length; i++)
		{
			if (Int32.TryParse(intStrArr[i], System.Globalization.NumberStyles.AllowLeadingSign, System.Globalization.CultureInfo.InvariantCulture, out parseResult))
				intArr[i] = parseResult;
			else
				intArr[i] = 0;
		}
		return intArr;
	}
}
